# coding: UTF-8
'''
Created on 2011/04/26

@author: yang_wanjun
'''
from django.contrib import messages
from django.contrib.auth import authenticate, login
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.template.loader import get_template
from django.utils.translation import ugettext as _

def render_response(request, *args, **kwargs):
    kwargs['context_instance'] = RequestContext(request)
    return render_to_response(*args, **kwargs)

def loadTempalte(theme_file):
    tpl_file = 'themes/default/' + theme_file
    return get_template(tpl_file)

def login_post(request, username, password):
    ret = False 
    if not username or not password:
        messages.error(request, _("Error: Please input username and password!"))
        return ret;
    user = authenticate(username=username, password=password)
    if user:
        if user.is_active:
            login(request, user)
            ret = True
        else:
            messages.error(request, _("Error: User is not actived!"))
    else:
        messages.error(request, _("Error: username or password is wrong!"))
    return ret

def get_current_page(request):
    try:
        current_page = int(request.GET.get('page'))
    except:
        current_page = 1
    return current_page

def get_pages_context(object_list, page_index, page_size):
    """返回分页后的相关信息，包括当前页的数据列表和所有的页码
    """
    paginator = Paginator(object_list, page_size)
    # 返回的信息保存在字典中返回
    ctx = {}
    # 如果请求的页码超过了共页数，则返回 最后一页
    try:
        page_current = paginator.page(page_index)
    except (EmptyPage, InvalidPage):
        page_current = paginator.page(paginator.num_pages)
    # 把当前页的数据列表添加到返回值中
    ctx.update({'page_current':page_current})
    # 把所有的页码添加到返回值中
    if paginator.num_pages > 1:
        ctx.update({'page_range':paginator.page_range})
    else:
        ctx.update({'page_range':[]})
    return ctx
